#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>//inet_pton 将点分十进制的 IP 地址转换为网络字节序的二进制格式，
                       //存储在 struct in_addr 中。
                        //这对于设置套接字的地址或解析主机名非常有用。
#include <unistd.h>//提供 close 函数
#include <thread>
using namespace std;
#define PORT 8080
#define BUFFER_SIZE 1024 //==char buffer [1024]={0} 
//定义缓冲区大小
//
void handle_receive(int sock) {
    char buffer[BUFFER_SIZE] = {0};
    while (true) {
        int num_bytes = recv(sock, buffer, BUFFER_SIZE - 1, 0);
        if (num_bytes <= 0) break; // 连接关闭或错误

        buffer[num_bytes] = '\0';
        std::cout << "Server: " << buffer << std::endl;
    }
    close(sock);
}

void handle_send(int sock) {
    std::string message;
    while (true) {
        std::cout << "Enter message: ";
        std::getline(std::cin, message);

        if (send(sock, message.c_str(), message.size(), 0) < 0) {
            std::cerr << "Send error" << std::endl;
            break;
        }
    }
    close(sock);
}

int main() {
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        std::cerr << "Socket creation failed" << std::endl;
        return 1;
    }

    struct sockaddr_in serv_addr;
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);
    if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
        std::cerr << "Invalid address/ Address not supported" << std::endl;
        close(sock);
        return 1;
    }

    if (connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
        std::cerr << "Connection Failed" << std::endl;
        close(sock);
        return 1;
    }

    std::thread receive_thread(handle_receive, sock);
    std::thread send_thread(handle_send, sock);

    receive_thread.join(); // 等待接收线程结束
    send_thread.join(); // 等待发送线程结束

    return 0;
}